#include "genericlistmodel.h"
#include <QMetaProperty>

#define firstRole (Qt::UserRole + 1)

GenericListModel::GenericListModel(QObject *parent, QMetaObject *metaObject) :
    QAbstractListModel(parent)
{
    roles = QAbstractListModel::roleNames();

    for(int i=0; i<metaObject->propertyCount(); i++) {
        roles.insert(i+firstRole, QByteArray(metaObject->property(i).name()) );
    }
}

GenericListModel::~GenericListModel()
{
    clearEntries();
}

void GenericListModel::clearEntries()
{
    for(int i=0; i<m_entries.length(); i++) {
        if(m_entries[i]->parent() == this) {
            delete m_entries[i];
        }
    }

    m_entries = QList<QObject *>();
}

int GenericListModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_entries.count();
}

QVariant GenericListModel::data(const QModelIndex &index, int role) const
{
    QVariant result;

    if(index.isValid()) {
        QObject *o = m_entries.value(index.row());
        result = o->metaObject()->property(role-firstRole).read(o);
    }

    return result;
}

QHash<int, QByteArray> GenericListModel::roleNames() const
{
    return roles;
}

void GenericListModel::setEntries(const QList<QObject *> &entries)
{
    clearEntries();

    for(int i=0; i<entries.length(); i++) {
        entries[i]->setParent(this);
    }

    m_entries = entries;
}

QList<QObject*> GenericListModel::getEntries()
{
    return m_entries;
}

QObject* GenericListModel::parent()
{
    return QAbstractListModel::parent();
}

void GenericListModel::setParent(QObject *parent)
{
    QAbstractListModel::setParent(parent);
}
